package com.youbo.ysqd.tools;


import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * post
 */
@Component
public class HttpAsyncUtils {



    public static void main(String[] argv) {


        String url="https://carrier.wbtech.com/api/login";
        Map<String,String> map=new HashMap<>();
        map.put("username","admin");
        map.put("password", "123456");

        HttpAsyncUtils s=new HttpAsyncUtils();


        for (int i = 0; i < 3; i++) {

            s.post(url, JSON.toJSONString(map), null, new Callback() {
                @Override
                public void completed(String content) {
                    System.out.println("----------- "+content);
                }
            });

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }
        }


    }

    RequestConfig requestConfig;
    IOReactorConfig ioReactorConfig;
    //设置连接池大小
    ConnectingIOReactor ioReactor=null;
    PoolingNHttpClientConnectionManager connManager;
    public HttpAsyncUtils(){

        requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000)
                .setSocketTimeout(50000)
                .setConnectionRequestTimeout(3)//设置为10ms
                .build();

        //配置io线程
        ioReactorConfig = IOReactorConfig.custom().
                setIoThreadCount(Runtime.getRuntime().availableProcessors())
                .setSoKeepAlive(true)
                .build();
        try {
            ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
        } catch (IOReactorException e) {
            e.printStackTrace();
        }

        connManager = new PoolingNHttpClientConnectionManager(ioReactor);
        connManager.setMaxTotal(20);//最大连接数设置1
        connManager.setDefaultMaxPerRoute(10);//per route最大连接数设置1


    }



    public void post(String url,String json,String token,Callback callback){
        CloseableHttpAsyncClient client=null;
        try{
            client = HttpAsyncClients.custom().
                    setConnectionManager(connManager)
                    .setDefaultRequestConfig(requestConfig)
                    .build();

            final HttpPost request = new HttpPost(url);
            request.addHeader("Content-Type","application/json");
            request.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36");
            if(null!=token){
                request.addHeader("Cookie","tk="+ token +"; sidebarStatus=0;");
            }

            StringEntity se;
            try {
                se = new StringEntity(json);
                se.setContentType("text/json");
                request.setEntity(se);
            }catch (Exception e){}

            client.start();

            client.execute(request, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse httpResponse) {
                    try {
                        String content = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                        if(null!=callback){
                            callback.completed(content);
                        }
                    } catch (IOException e) {}
                }

                @Override
                public void failed(Exception e) {
                }
                @Override
                public void cancelled() {
                }
            });
        }catch (Exception e){

        }finally {
            if(null!=client){
                try {
//                    client.notifyAll();
//                    client.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }




    }





}

